from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework_jwt.settings import api_settings
from rest_framework import status

from .utils import OAuthQQ
from .models import OAuthQQUser
from .exceptions import QQAPIException
from . import serializers
from carts.utils import merge_cart_cookie_to_redis


class QQAuthUserView(GenericAPIView):

    """用户扫码登录的回调处理"""
    # 需要指定序列化器
    serializer_class = serializers.QQAuthUserSerializer

    def get(self, request):
        # 提取code参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建oauth工具对象
        oauth = OAuthQQ()

        try:
            # 使用code向服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使用access_token向qq服务器请求openid
            openid = oauth.get_openid(access_token)

        except QQAPIException:
            return Response({'message': 'qq服务器异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 使用openid查询该qq用户是否在美多商城中绑定过用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没有绑定美多商城的用户，创建用户并且绑定到openid
            # 用户第一次使用qq登录
            access_token_openid = oauth.generate_save_user_token(openid)
            return Response({'access_token': access_token_openid})
        else:
            # 如果openid已经绑定了美多商城用户，直接生成jwt token， 并返回
            user = oauth_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)
            return response
            # pass

    def post(self, request):
        """绑定用户到openid"""

        # 获取序列化器
        serilizer = self.get_serializer(data=request.data)

        # 开启校验
        serilizer.is_valid(raise_exception=True)

        user = serilizer.save()

        # 生成已经登录的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'user_id': user.id,
            'token': token,
            'username': user.username
        })
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)
        return response


#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        next = request.query_params.get('next')

        # 创建oauth工具对象
        oauth = OAuthQQ(state=next)

        # 调用获取qq登陆界面的url的工具方法
        login_url = oauth.get_qq_login_url()

        # 返回qq登陆界面的url给浏览器
        return Response({'login_url': login_url})


